package com.buildings.http;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.buildings.activity.LoginActivity;
import com.buildings.activity.MainTabActivity;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseApplication;
import com.buildings.bean.LoginBean;
import com.buildings.util.Base64Test;
import com.buildings.util.CustomToast;
import com.buildings.util.SPUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * Created by songwei on 2017/3/6.
 */

public class OkHttpManager {


    private static OkHttpManager httpManager;

    private OkHttpClient mOkHttpClient;

    private Handler mHandler;

    private Gson mGson;


    private OkHttpManager() {

        initOkHttp();
        mHandler = new Handler(Looper.getMainLooper());
        mGson = new Gson();
    }

    public static synchronized OkHttpManager getHttpManager() {

        if (httpManager == null)
            httpManager = new OkHttpManager();
        return httpManager;

    }

    private void initOkHttp() {

        mOkHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20000, TimeUnit.SECONDS)
                .connectTimeout(20000, TimeUnit.SECONDS)
                .writeTimeout(20000, TimeUnit.SECONDS)
                .cookieJar(new CookiesManager())
                .build();
    }


    public void request(MyHttpClient client, final BaseCallBack callBack) {


        if (callBack == null) {

            throw new NullPointerException("callback is null");
        }

        mOkHttpClient.newCall(client.buildRequest()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                sendonFailureMessage(callBack, call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {

                    String str = response.body().string();
                    Log.e("服务器返回数据= ", str);
                    int isLogin = (int) SPUtil.get("isLogin",0);
                    if(isLogin == 1){//登陆才判断
                        try {
                            JSONObject jsonObject = new JSONObject(str);
                            int code = jsonObject.getInt("code");
                            if(code == 401){
                                //token失效了，需要重新登陆
                                String phone = (String) SPUtil.get("phone","");
                                String password = (String) SPUtil.get("password","");
                                login(phone,password);

                            }else if(code == 417){
                                SPUtil.save("isLogin",0);
                                BaseApplication.getInstance().sendBroadcast(new Intent("action.logout"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    if (callBack.mType == null || callBack.mType == String.class) {

                        sendonSuccessMessage(callBack, str);
                    } else {

                        try {
                            sendonSuccessMessage(callBack, mGson.fromJson(str, callBack.mType));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Log.e("========自动解析失败了========", "");
                            sendonErrorMessage(callBack, response.code());
                        }
                    }

                    if (response.body() != null) {

                        response.body().close();
                    }
                } else {

                    sendonErrorMessage(callBack, response.code());
                }

            }
        });

    }

    private void sendonFailureMessage(final BaseCallBack callBack, final Call call, final IOException e) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {

                callBack.onFailure(call, e);
                Log.e("请求异常代码 ", e.getLocalizedMessage());
//                CustomToast.showToast(App.getInstance(), "网络错误");
            }
        });

    }

    private void sendonErrorMessage(final BaseCallBack callBack, final int code) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {

                callBack.onError(code);
                Log.e("请求错误Code ", code + "");
            }
        });

    }

    private void sendonSuccessMessage(final BaseCallBack callBack, final Object object) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {

                callBack.onSuccess(object);

            }
        });

    }


    private void login(final String phone, String password) {

        JsonBuilder jsonBuilder = new JsonBuilder(null);
        jsonBuilder.put("cipher", password);
        jsonBuilder.put("appCode", Constant.APP_CODE);

        MyHttpClient
                .newBuilder()
                .post()
                .url(Api.LOGIN+"/"+phone+"/loginauth")
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean bean) {
                        super.onSuccess(bean);
//{"code":200,"data":{"success":true,"errorCode":null,"errorMessage":null,"retryTimes":0,"remainLockedTime":null,"userId":"ca3ca0d0d557424d94ec8009b6ca6d08","token":"eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiJhNGQ1MTkxZC01ZjY0LTQ5YjEtYTk4NS01NjM2YTA5ZDc1M2EiLCJpYXQiOjE1ODk1MzMxNDksInN1YiI6IjkzNWQ4MzNkZGU0MjRlMWJhYzdmZWVjM2M0MDZhMDI5IiwiZXhwIjoxNTg5NTMzNTQ5fQ.KGhav1E8SLuHXkb60RsbWj3xLMscIPrGmvDSmPjSLr4"},"message":null}
                        if(bean != null && bean.getCode() == 401){
                            if(bean.getData().isSuccess()){
                                SPUtil.save("token",bean.getData().getToken());
                                SPUtil.save("userId",bean.getData().getUserId());
                                SPUtil.save("isLogin",1);

                            }else {
                                SPUtil.save("isLogin",0);
                                BaseApplication.getInstance().sendBroadcast(new Intent("action.logout"));
                            }
                        }else {
                            SPUtil.save("isLogin",0);
                            BaseApplication.getInstance().sendBroadcast(new Intent("action.logout"));

                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        BaseApplication.getInstance().sendBroadcast(new Intent("action.logout"));
                        SPUtil.save("isLogin",0);

                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        BaseApplication.getInstance().sendBroadcast(new Intent("action.logout"));
                        SPUtil.save("isLogin",0);
                    }
                });

    }


}